#include "dialog.h"
#include "ui_dialog.h"
#include "mythread.h"

struct myaddr dev;
Dialog::Dialog(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::Dialog)
{
    ui->setupUi(this);
    udp_socket=new QUdpSocket(this);
    tcp_socket=new QTcpSocket(this);
    connect(ui->pushButtonConnect,SIGNAL(clicked()),this,SLOT(btnTCP_ConnectSlot()));
    connect(ui->pushButtonSerch,SIGNAL(clicked()),this,SLOT(btnUDP_ConnectSlot()));
    connect(udp_socket, SIGNAL(readyRead()),this,SLOT(searchDeviceSlot()));
    connect(ui->listWidget, SIGNAL(itemClicked(QListWidgetItem*)), this, SLOT(listWidget_Clicked(QListWidgetItem*)));
}

Dialog::~Dialog()
{
    delete ui;
}

void Dialog::btnUDP_ConnectSlot()
{
    QHostAddress ip ("192.168.51.255");
    quint16 port = 8888;
    udp_socket->writeDatagram("coffee", ip, port);
}

void Dialog::searchDeviceSlot()
{
    if(udp_socket->hasPendingDatagrams())
    {
        QHostAddress host;
        QByteArray data;
        quint16 port;
        data.resize(udp_socket->pendingDatagramSize());
        udp_socket->readDatagram(data.data(), data.size(), &host, &port);
        QString text=QString(data);
        dev.myhost=host;
        dev.myport=port;
        dev.myname=text.mid(8);
        qDebug()<<host.toString()<<"    "<<port<<"    "<<text;
        if(text.startsWith("yes"))
        {
            QString buf = QString("IP:%1, Post:%2").arg(host.toString()).arg(port);
            ui->listWidget->insertItem(1,buf);
        }
    }
}
void Dialog::btnTCP_ConnectSlot()
{
    tcp_socket->connectToHost(dev.myhost.toString(),dev.myport);
    connect(tcp_socket, SIGNAL(connected()),this,SLOT(SendOneSlot()));
}

void Dialog::listWidget_Clicked(QListWidgetItem *item)
{
    QString buf = item->text();
    ui->lineEdit->setText(buf);
}
void Dialog::SendOneSlot()
{
    qDebug() << "连接成功！";
    QJsonObject ject;
    ject.insert("type",1);
    QJsonDocument doc(ject);
    QByteArray json = doc.toJson();
    tcp_socket->write(json);
    connect(tcp_socket, SIGNAL(readyRead()),this,SLOT(ReceiveOneSlot()));

    //            if(obj.contains("data"))
    //            {
    //                QJsonValue value = obj.value("data");
    //                if(value.isObject())
    //                {
    //                    QJsonObject subobj = value.toObject();
    //                    if(subobj.contains("flag"))
    //                    {
    //                        QJsonValue subValue = subobj.value("flag");
    //                        QString flag = subValue.toString();
    //                        qDebug() << "flag : " << flag;
    //                    }
    //                }
    //            }



}
void Dialog::ReceiveOneSlot()
{
    //  读取数据
    QByteArray data =  tcp_socket->readAll();
    qDebug() << "接收到的数据：" << data;
    //QJsonParseError jsonError;
    QJsonDocument doc = QJsonDocument::fromJson(data);
    if(doc.isObject())
    {
        qDebug() << "OK!!!!" << endl;
        QJsonObject obj = doc.object();

        if(obj.contains("type"))
        {
            QJsonValue value1 = obj.value("type");
            int type = value1.toInt();
            qDebug() << "type : " << type;
        }

        if(obj.contains("result"))
        {
            QJsonValue value2 = obj.value("result");
            int result = value2.toInt();
            qDebug() << "result : " << result;
        }
        if(obj.contains("up_config"))
        {
            QJsonValue value3 = obj.value("up_config");
            int up_config = value3.toInt();
            qDebug() << "up_config : " << up_config;
            if(up_config == 1)
            {
                qDebug() << "已存在";
            }
            else if(up_config == 0)
            {
                qDebug() << "不存在，已发送";
                //                QJsonObject ject;
                //                QJsonObject mqtt;
                //                QJsonObject video;
                //                QJsonObject update;
                //                QJsonObject data;
                //                ject.insert("type",1);
                //                ject.insert("result",0);
                //                ject.insert("up_config","false");
                //                ject.insert("data","1");
                //                mqtt.insert("mqtt_addr","1");
                //                mqtt.insert("mqtt_port",1);
                //                video.insert("video_addr","1");
                //                video.insert("video_port",1);
                //                update.insert("type",1);
                //                update.insert("period",5);
                //                data.insert("mqtt_config",mqtt);
                //                data.insert("video_config",video);
                //                data.insert("update_config",update);
                //                ject.insert("data",data);
                //                QJsonDocument doc(ject);
                //                QByteArray json = doc.toJson();
                //                tcp_socket->write(json);

                QFile file(".\\config.json");
                if (!file.exists())
                {
                    qDebug() << "File does not exist!";
                    return;
                }
                if (!file.open(QIODevice::ReadOnly))
                {
                    qDebug() << "无法打开";
                    tcp_socket->close();
                    return;
                }
                QByteArray buffer;
                while (!file.atEnd())
                {
                    buffer = file.read(1024); // 每次读取 1024 字节
                    tcp_socket->write(buffer);
                }
                tcp_socket->flush();
                tcp_socket->waitForBytesWritten();
            }
        }
    }
}
